<template>
  <div class="plan-main-box">
    <div class="add-pur-box">
      <div class="box-head">新建采购计划</div>
      <div class="my-form-style">
        <el-form ref="purForm" :model="purForm" :rules="rules">
          <div class="box-plan-info">
            <div>基本信息</div>
            <div class="basic-info">
              <span>计划编号:</span>
              <el-input class="my_style" disabled value="系统自动生成" />
            </div>
            <div class="basic-info">
              <el-form-item
                label="计划名称"
                prop="planName"
                label-width="130px"
              >
                <el-input class="my_style" v-model="purForm.planName" />
              </el-form-item>
            </div>
            <div class="basic-info">
              <el-form-item
                label="业务类型"
                prop="busiType"
                label-width="120px"
              >
                <el-select
                  placeholder="请选择业务类型"
                  clearable
                  class="my_style"
                  v-model="purForm.busiType"
                >
                  <el-option
                    v-for="dict in dict.type.business_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="basic-info">
              <span style="margin-left: 65px">创建人:</span>
              <el-input class="my_style" disabled v-model="purForm.creater" />
            </div>
            <div class="basic-info">
              <span>创建部门:</span>
              <el-input class="my_style" disabled v-model="purForm.deptName" />
            </div>
            <div class="basic-info" style="width: 500px">
              <span style="float: left; margin-right: 20px">上传附件:</span>
              <el-upload
                ref="upload"
                :action="upload.url"
                :headers="upload.headers"
                :file-list="upload.fileList"
                :multiple="true"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :limit="5"
                :on-exceed="exceedingMaximumLimit"
                :on-error="uploadError"
                :before-upload="beforeUpload"
                :before-remove="beforeRemove"
                :on-remove="removeFile"
                :auto-upload="false"
              >
                <el-button slot="trigger" size="small" type="primary"
                  >选取文件</el-button
                >
                <el-button
                  style="margin-left: 10px"
                  size="small"
                  type="success"
                  :loading="upload.isUploading"
                  @click="submitUpload"
                  >上传到服务器
                </el-button>
              </el-upload>
            </div>
          </div>
        </el-form>
      </div>
      <div class="budget-box">
        <div>预算信息</div>
        <div class="budget-info">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['budget:budget:add']"
                >新增</el-button
              >

              <el-button
                type="info"
                plain
                size="mini"
                @click="budGetsortedArray"
                >格式化</el-button
              >
            </el-col>
          </el-row>

          <el-table
            :data="budgetList"
            :span-method="objectSpanMethod"
            ref="multipleBudgetTable"
            border
            @selection-change="handleSelectionBudgetChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <!-- 添加序号列 -->
            <el-table-column
              label="序号"
              type="index"
              width="50"
              align="center"
              index-method="indexMethod"
            />
            <el-table-column label="预算编号" align="center" prop="bgId" />
            <el-table-column
              label="部门名称"
              align="center"
              prop="createPost"
            />
            <el-table-column
              label="预算名称"
              align="center"
              prop="bgName"
              width="200px"
            />

            <el-table-column label="总金额" align="center" prop="totalAmount" />

            <el-table-column
              label="已使用金额"
              align="center"
              prop="useMoney"
            />
            <el-table-column label="剩余金额" align="center" prop="surpMoney" />

            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.$index, scope.row)"
                  v-hasPermi="['budget:budget:edit']"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.$index, scope.row)"
                  v-hasPermi="['budget:budget:remove']"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 添加或修改采购对话框 -->
          <el-dialog
            :title="title"
            :visible.sync="open"
            width="500px"
            append-to-body
          >
            <el-form
              ref="form"
              :model="form"
              :rules="bgRules"
              label-width="80px"
            >
              <el-form-item label="预算编号" prop="planCode">
                <el-input value="系统自动生成" disabled />
              </el-form-item>
              <el-form-item label="部门名称" prop="createPost">
                <el-input
                  v-model="form.createPost"
                  placeholder="请输入部门名称"
                />
              </el-form-item>
              <el-form-item label="预算名称" prop="bgName">
                <el-input v-model="form.bgName" placeholder="请输入预算名称" />
              </el-form-item>
              <el-form-item label="总金额" prop="totalAmount">
                <el-input
                  v-model="form.totalAmount"
                  placeholder="请输入总金额"
                />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </el-dialog>
        </div>
      </div>

      <!--物料明细-->
      <div class="pro-box">
        <div>物料明细</div>
        <div class="planPro-info">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="addPlanInfo"
            >新增</el-button
          >
          <el-button
            type="primary"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="updatePlanInfo"
            >修改</el-button
          >
          <el-button
            type="danger"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="removeSelectedRows"
            >删除</el-button
          ><el-button type="info" plain size="mini" @click="test"
            >格式化</el-button
          >

          <el-table
            :data="planInfoList"
            :span-method="productObjectSpanMethod"
            @selection-change="handleSelectionProductChange"
            ref="multipleProductTable"
            border
            style="margin-top: 10px"
          >
            <!-- 添加序号列 -->
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="序号"
              type="index"
              width="50"
              align="center"
              index-method="indexMethod"
            />

            <el-table-column
              label="预算编号"
              align="center"
              prop="bgId"
              width="150"
            >
              <template slot-scope="scope">
                <div
                  class="budGetSty"
                  @click="myPlanProIndex(scope.$index)"
                  v-show="!scope.row.bgId"
                ></div>
                <div
                  v-show="scope.row.bgId"
                  @click="changePro(scope.$index, scope.row)"
                  class="Pro-BudGet-Sty"
                >
                  {{ scope.row.bgId }}
                </div>
              </template>
            </el-table-column>

            <el-table-column
              label="产品编号"
              align="center"
              prop="prodId"
              width="200"
            >
              <template slot-scope="scope">
                <div
                  class="planProSty"
                  @click="myPlanProduct(scope.$index)"
                  v-show="!scope.row.prodId"
                ></div>
                <div
                  v-show="scope.row.prodId"
                  @click="changeProduct(scope.$index, scope.row)"
                  class="product-style"
                >
                  {{ scope.row.prodId }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="产品名称"
              align="center"
              prop="prodName"
              width="120"
            />

            <el-table-column
              label="规格"
              align="center"
              prop="size"
              width="140"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.size"
                  style="border-bottom: 1px solid #ccc"
                  v-show="scope.row.statu"
                ></el-input>
                <div v-show="!scope.row.statu">{{ scope.row.size }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="税率(%)"
              align="center"
              prop="taxRate"
              width="180"
            >
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.taxRate"
                  controls-position="right"
                  @change="handleChangeRate"
                  v-show="scope.row.statu"
                  :min="1"
                  :max="10"
                  style="
                    width: 120px;
                    border: 1px solid #ccc;
                    border-radius: 5px;
                  "
                ></el-input-number>
                <div v-show="!scope.row.statu">{{ scope.row.taxRate }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="预算单价"
              align="center"
              prop="bdgSinglePrice"
              width="120"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.bdgSinglePrice"
                  style="border-bottom: 1px solid #ccc"
                  @input="
                    handleInputChange(scope.$index, scope.row.bdgSinglePrice)
                  "
                  v-show="scope.row.statu"
                ></el-input>
                <div v-show="!scope.row.statu">
                  {{ scope.row.bdgSinglePrice }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="需求数量"
              align="center"
              prop="reqNumber"
              width="220"
            >
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.reqNumber"
                  @change="handleChange(scope.$index, scope.row.reqNumber)"
                  v-show="scope.row.statu"
                  :min="0"
                  :max="99999"
                  label="描述文字"
                  class="el-inputNumber-style"
                ></el-input-number>
                <div v-show="!scope.row.statu">{{ scope.row.reqNumber }}</div>
              </template>
            </el-table-column>

            <el-table-column
              label="预算总价"
              align="center"
              prop="bdgTotlePrice"
              width="120"
            />

            <el-table-column
              label="交付时间"
              align="center"
              prop="delvTime"
              width="220"
            >
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.delvTime"
                  type="date"
                  placeholder="选择日期"
                  @change="handleDateChange(scope.$index, scope.row.delvTime)"
                  class="datePickerStyle"
                  style="width: 150px"
                >
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column
              label="需求说明"
              align="center"
              prop="prodExplain"
              width="200"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.prodExplain"
                  style="border-bottom: 1px solid #ccc"
                  v-show="scope.row.statu"
                ></el-input>
                <div v-show="!scope.row.statu">{{ scope.row.prodExplain }}</div>
              </template></el-table-column
            >
            <el-table-column
              label="采购人"
              align="center"
              prop="purchaser"
              width="120"
            />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="changeStatu(scope.$index)"
                  >确定</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div>
        <el-dialog
          title="提示"
          :visible.sync="dialogVisible"
          width="55%"
          :before-close="handleClose"
        >
          <div>
            <el-table
              :data="budgetList"
              :span-method="objectSpanMethod"
              border
              @row-dblclick="getBudGetRow"
            >
              <!-- 添加序号列 -->
              <el-table-column
                label="序号"
                type="index"
                width="50"
                align="center"
                index-method="indexMethod"
              />
              <el-table-column
                label="预算编号"
                width="150px"
                align="center"
                prop="bgId"
              />
              <el-table-column
                label="部门名称"
                width="140px"
                align="center"
                prop="createPost"
              />
              <el-table-column
                label="预算名称"
                align="center"
                prop="bgName"
                width="200px"
              />

              <el-table-column
                label="总金额"
                align="center"
                prop="totalAmount"
              />

              <el-table-column
                label="已使用金额"
                align="center"
                prop="useMoney"
                width="100"
              />
              <el-table-column
                label="剩余金额"
                align="center"
                prop="surpMoney"
              />

              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
                width="120"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="getBudGetRow(scope.row)"
                    >确定</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogVisible = false"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </div>
      <div>
        <el-dialog
          title="提示"
          :visible.sync="dialogVisible2"
          width="65%"
          :before-close="handleClose2"
        >
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="mini"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
            style="margin-left: 50px"
          >
            <el-form-item label="产品名称" prop="prodName">
              <el-input
                v-model="queryParams.prodName"
                placeholder="请输入产品名称"
                clearable
                @keyup.enter.native="handleQuery"
                style="border: 1px solid #ccc; border-radius: 5px"
              />
            </el-form-item>
            <el-form-item label="产品类型" prop="prodType">
              <el-select
                v-model="queryParams.prodType"
                placeholder="请选择产品类型"
                clearable
                style="border: 1px solid #ccc; border-radius: 5px"
              >
                <el-option
                  v-for="dict in dict.type.basic_product_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>

          <el-table
            ref="multipleTable"
            :data="productList"
            @selection-change="handleSelectionChange"
            border
            style="
              width: 800px;
              margin-left: 20px;
              height: 400px;
              overflow: auto;
            "
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
              :selectable="checkSelectable"
            />

            <!-- 添加序号列 -->
            <el-table-column
              label="序号"
              type="index"
              width="50"
              align="center"
              index-method="indexMethod"
            />
            <el-table-column
              label="产品编号"
              align="center"
              prop="prodId"
              width="150px"
            />
            <el-table-column
              label="产品名称"
              align="center"
              prop="prodName"
              width="200px"
            />
            <el-table-column
              label="产品类型"
              align="center"
              prop="prodType"
              width="100px"
            >
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.basic_product_type"
                  :value="scope.row.prodType"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="物料单位"
              align="center"
              prop="prodUnit"
              width="120px"
            >
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.basic_product_unit"
                  :value="scope.row.prodUnit"
                />
              </template>
            </el-table-column>

            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="saveProduct(scope.row)"
                  :disabled="productOpenCode == 1"
                  >确定</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />

          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible2 = false">取 消</el-button>
            <el-button type="primary" @click="addProductByBueGetBatch"
              >确 定</el-button
            >
          </span>
        </el-dialog>
        <div class="submit-box">
          <el-button
            type="primary"
            style="margin-left: 1000px"
            @click="generatePurPlan"
            >提 交</el-button
          >
          <el-button type="info">取 消</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
  
  <script>
import fileLoad from "@/components/FileUpload/index";
import { addPlanFiles, delPlanFiles } from "@/api/planFiles/planFiles";
import { budList } from "@/api/budget/budget";
import utils from "@/api/utils/utils.js";
import { getPurCode, deleteFile, addPurs } from "@/api/purs/purs";
import { addBatchPlanInfo, getPlanInfoNewId } from "@/api/purs/planInfo";
import { listProduct } from "@/api/basic/product";
import { addRecords } from "@/api/purs/records";
import { getToken } from "@/utils/auth";
export default {
  dicts: ["basic_product_unit", "basic_product_type", "business_type"],
  data() {
    return {
      // 遮罩层
      selectionBudGet: [],
      // 采购表格数据
      budgetList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层

      open: false,
      // 查询参数
      dialogVisible: false,
      dialogVisible2: false,
      addFileList: [],
      purForm: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planCode: [
          { required: true, message: "计划编码不能为空", trigger: "blur" },
        ],
        planName: [
          { required: true, message: "计划名称不能为空", trigger: "blur" },
        ],
        busiType: [
          { required: true, message: "业务类型不能为空", trigger: "change" },
        ],
        creater: [
          { required: true, message: "创建人不能为空", trigger: "blur" },
        ],
        deptName: [
          { required: true, message: "创建部门不能为空", trigger: "blur" },
        ],
        loadFileId: [
          { required: true, message: "上传附件不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "审批状态不能为空", trigger: "change" },
        ],
        prodMethod: [
          { required: true, message: "采购方式不能为空", trigger: "blur" },
        ],
        planType: [
          { required: true, message: "计划类型不能为空", trigger: "change" },
        ],
      },
      fileList: [],
      budgetList: [],
      bgRules: {
        bgName: [
          { required: true, message: "预算名称不能为空", trigger: "change" },
        ],
        totalAmount: [
          { required: true, message: "总金额不能为空", trigger: "change" },
        ],
      },

      /**文件上传 */
      file: {
        fileUrls: [],
        fileName: [],
      },
      //上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/purs/file/upload",
        // 上传的文件列表
        fileList: [],
        //上传成功列表
        fileSecuss: [],
      },

      //附件对象
      fileForm: {},
      //提交状态 1.新增 2.修改
      submitStatu: 0,
      //修改对象的索引
      updateObjIndex: "",
      budGetCodeIndex: "",
      //需要添加的预算对象集合
      addBudGetList: [],
      budGetCodeObj: {},
      addPurPlanStatu: true,

      //物料明细
      planInfoList: [],
      planForm: {},
      planProIndex: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        prodName: null,
        prodType: null,
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      productList: [],
      productIndex: "",
      product: "",
      selectProList: [],
      productOpenCode: 1,
      multipleSelection: [],
      multipleProductSelection: [],
      multiplebudgetSelection: [],
      //监听预算编号相关总价
      totalBudGet: 0,
      budGetCodeByIndex: "",
      producByIndex: -1,
      beforPlan: {},
      incry: 0,
      saveList: [],
      addObjIndex: 0,
      changeMoneyStatu: true,
      updateProduct: {},
      productStatu: 0,
      openupdateProduct: true,
      updateProductList: [],
      backProduct: {},
      records: {},
    };
  },
  watch: {},
  components: {
    fileLoad,
  },
  mounted() {
    this.purForm.creater = sessionStorage.getItem("userName");
    this.purForm.deptName = sessionStorage.getItem("deptName");
  },
  created() {
    this.getPlanCode();
  },
  methods: {
    submitAll() {
      this.budList();
    },

    budGetsortedArray() {
      return this.budgetList.sort((a, b) => {
        const nameA = a.createPost,
          nameB = b.createPost;
        const len = Math.min(nameA.length, nameB.length);
        for (let i = 0; i < len; i++) {
          const charA = nameA.charCodeAt(i),
            charB = nameB.charCodeAt(i);
          if (charA !== charB) {
            return charA - charB; // 根据Unicode编码排序
          }
        }
        return nameA.length - nameB.length; // 如果前len个字符相同，则比较长度
      });
    },

    sortedArray() {
      return this.planInfoList.sort((a, b) => {
        const nameA = a.bgId,
          nameB = b.bgId;
        const len = Math.min(nameA.length, nameB.length);
        for (let i = 0; i < len; i++) {
          const charA = nameA.charCodeAt(i),
            charB = nameB.charCodeAt(i);
          if (charA !== charB) {
            return charA - charB; // 根据Unicode编码排序
          }
        }
        return nameA.length - nameB.length; // 如果前len个字符相同，则比较长度
      });
    },
    test() {
      console.log(`output->123`, 123);
      console.log(this.sortedArray());
    },
    handleSelectionProductChange(val) {
      this.multipleProductSelection = val;
    },
    handleSelectionBudgetChange(val) {
      this.multipleProductSelection = val;
    },
    removeSelectedRows() {
      console.log("update:" + JSON.stringify(this.updateProductList));
      this.multipleProductSelection.forEach((item) => {
        if (this.updateProductList.length > 0) {
          this.updateProductList.forEach((obj) => {
            if (obj.id === item.id) {
              this.updateProductList = this.updateProductList.filter(
                (obj) => obj.id !== item.id
              );
              const index = this.budgetList.findIndex(
                (budgetItem) => budgetItem.bgId === item.bgId
              );
              if (index != -1) {
                this.budgetList[index].useMoney = parseFloat(
                  this.budgetList[index].useMoney - item.bdgTotlePrice
                ).toFixed(2);
                this.budgetList[index].surpMoney = parseFloat(
                  this.budgetList[index].totalAmount -
                    this.budgetList[index].useMoney
                ).toFixed(2);
              }
            }
          });
        }
      });

      console.log("update:" + JSON.stringify(this.updateProductList));
      let obj = this.multipleProductSelection;
      // 遍历选中的行并从 tableData 中移除
      this.planInfoList = this.planInfoList.filter(
        (item) => !this.multipleProductSelection.includes(item)
      );

      // 清空 multipleSelection
      this.multipleProductSelection = [];
      // 清空表格的选择状态
      this.$refs.multipleProductTable.clearSelection();
    },
    delBudgetListBySelection() {
      // 遍历选中的行并从 tableData 中移除
      this.budgetList = this.budgetList.filter(
        (item) => !this.multiplebudgetSelection.includes(item)
      );

      // 清空 multipleSelection
      this.multiplebudgetSelection = [];
      // 清空表格的选择状态
      this.$refs.multipleProductTable.clearSelection();
    },
    handleInputChange(index, value) {
      this.handleChange(index, value);
    },
    changeStatu(index) {
      this.planInfoList[index].statu = false;
    },
    handleDateChange(index, value) {
      this.planInfoList[index].delvTime = this.myFormatTime(value);
    },
    changeProduct(index, item) {
      this.productIndex = index;
      this.dialogVisible2 = true;
      this.productOpenCode = 2;
    },
    addProductByBueGetBatch() {
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (i == 0) {
          this.addObjIndex++;
          let obj = this.planInfoList[this.productIndex];
          obj.id = this.addObjIndex;
          obj.prodId = this.multipleSelection[i].prodId;
          obj.prodName = this.multipleSelection[i].prodName;
          obj.purchaser = this.purForm.creater;
          this.planInfoList.splice(this.productIndex, 1);
          this.planInfoList.splice(this.productIndex, 0, obj);
        } else {
          this.addObjIndex++;
          let obj = {};
          obj.id = this.addObjIndex;
          obj.bgId = this.planInfoList[this.productIndex].bgId;
          obj.prodId = this.multipleSelection[i].prodId;
          obj.purchaser = this.purForm.creater;
          obj.prodName = this.multipleSelection[i].prodName;
          obj.taxRate = 1;

          obj.statu = true;
          obj.reqNumber = 1;
          this.planInfoList.push(obj);
        }
      }
      this.multipleSelection = [];
      this.$refs.multipleTable.clearSelection();

      this.dialogVisible2 = false;
    },
    saveProduct(item) {
      let nowObj = this.planInfoList[this.productIndex];
      let obj = {};
      if (nowObj.bgId) {
        obj.bgId = nowObj.bgId;
      }
      if (nowObj.prodId) {
        obj.prodId = nowObj.prodId;
      }
      if (nowObj.reqNumber) {
        obj.reqNumber = nowObj.reqNumber;
      }
      if (nowObj.size) {
        obj.size = nowObj.size;
      }
      if (nowObj.taxRate) {
        obj.taxRate = nowObj.taxRate;
      }
      if (nowObj.bdgSinglePrice) {
        obj.bdgSinglePrice = nowObj.bdgSinglePrice;
      }
      if (nowObj.delvTime) {
        obj.delvTime = this.myFormatTime(nowObj.delvTime);
      }
      if (nowObj.delvPlace) {
        obj.delvPlace = nowObj.delvPlace;
      }
      if (nowObj.prodExplain) {
        obj.prodExplain = nowObj.prodExplain;
      }
      if (nowObj.purchaser) {
        obj.purchaser = nowObj.purchaser;
      }
      if (nowObj.id) {
        obj.id = nowObj.id;
      }
      if (nowObj.statu) {
        obj.statu = nowObj.statu;
      }

      obj.prodId = item.prodId;
      obj.prodName = item.prodName;
      obj.purchaser = this.purForm.creater;
      this.product = obj;
      this.planInfoList.splice(this.productIndex, 1);
      this.planInfoList.splice(this.productIndex, 0, obj);
      this.dialogVisible2 = false;
    },
    handleClose2() {
      this.dialogVisible2 = false;
    },
    indexMethod(index) {
      // 根据需要自定义序号生成方式，这里只是简单返回索引+1
      return index + 1;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    myPlanProduct(index) {
      if (this.planInfoList[index].bgId != null) {
        this.productOpenCode = 1;
        this.productIndex = index;
        this.getList();
        this.dialogVisible2 = true;
      } else {
        this.$modal.msgError("请先填写该行数据预算信息");
      }
    },

    //物料明细开始
    changePro(index, item) {
      this.dialogVisible = true;
      this.planProIndex = index;
    },
    myPlanProIndex(index) {
      this.dialogVisible = true;
      this.planProIndex = index;
    },
    /** 查询产品列表 */
    getList() {
      listProduct(this.queryParams).then((response) => {
        this.productList = response.rows;
        this.total = response.total;
      });
    },
    addPlanInfo() {
      if (this.planInfoList.length > 0) {
        let nowObj = this.planInfoList[this.planInfoList.length - 1];
        if (
          nowObj.bgId == null ||
          nowObj.prodId == null ||
          nowObj.size == null ||
          nowObj.taxRate == null ||
          nowObj.bdgSinglePrice == null ||
          nowObj.reqNumber == null ||
          nowObj.bdgTotlePrice == null ||
          nowObj.delvTime == null ||
          nowObj.prodExplain == null ||
          nowObj.purchaser == null
        ) {
          this.$modal.msgError("信息填充不完整");
        } else {
          this.addObjIndex++;
          let obj = {};
          obj.id = this.addObjIndex;
          obj.reqNumber = 0;
          obj.statu = true;
          obj.purchaser = this.purForm.creater;
          obj.reqNumber = 1;
          this.beforPlan.bdgTotlePrice =
            this.planInfoList[this.productIndex].bdgTotlePrice;
          this.beforPlan.bgId = this.planInfoList[this.productIndex].bgId;
          obj.taxRate = 1;
          this.incry = 0;

          this.planInfoList.push(obj);
          console.log("obj:" + JSON.stringify(this.planInfoList));
          this.productStatu = 1;
        }
      } else {
        let obj = {};
        this.addObjIndex++;
        obj.id = this.addObjIndex;
        obj.purchaser = this.purForm.creater;
        obj.taxRate = 1;
        obj.statu = true;
        obj.reqNumber = 1;

        this.incry = 0;
        this.planInfoList.push(obj);
        this.productStatu = 1;
      }
    },

    handleChangeRate(value) {
      console.log(value);
    },
    handleClose() {
      this.dialogVisible = false;
    },

    getBudGetRow(item) {
      let nowObj = this.planInfoList[this.planProIndex];
      let obj = {};
      if (nowObj.bgId) {
        obj.bgId = nowObj.bgId;
      }
      if (nowObj.prodId) {
        obj.prodId = nowObj.prodId;
      }
      if (nowObj.reqNumber) {
        obj.reqNumber = nowObj.reqNumber;
      }
      if (nowObj.size) {
        obj.size = nowObj.size;
      }
      if (nowObj.taxRate) {
        obj.taxRate = nowObj.taxRate;
      }
      if (nowObj.bdgSinglePrice) {
        obj.bdgSinglePrice = nowObj.bdgSinglePrice;
      }
      if (nowObj.delvTime) {
        obj.delvTime = this.myFormatTime(nowObj.delvTime);
      }
      if (nowObj.delvPlace) {
        obj.delvPlace = nowObj.delvPlace;
      }
      if (nowObj.prodExplain) {
        obj.prodExplain = nowObj.prodExplain;
      }
      if (nowObj.purchaser) {
        obj.purchaser = nowObj.purchaser;
      }
      if (nowObj.id) {
        obj.id = nowObj.id;
      }
      if (nowObj.statu) {
        obj.statu = nowObj.statu;
      }
      obj.bgId = item.bgId;
      this.planInfoList.splice(this.planProIndex, 1);
      this.planInfoList.splice(this.planProIndex, 0, obj);
      this.dialogVisible = false;
    },
    updatePlanInfo() {
      if (this.multipleProductSelection.length > 0) {
        let obj = this.multipleProductSelection[0];
        if (this.multipleProductSelection.length > 1) {
          this.$modal.msgError("只能同时修改一条数据");
        } else {
          const index = this.planInfoList.findIndex(
            (item) => item.id === obj.id
          );
          this.planInfoList[index].statu = true;
        }
      } else {
        this.$modal.msgError("未选择要修改的数据");
      }
    },
    saveRowProduct(index) {
      const searchIndex = this.budgetList.findIndex(
        (item) => item.bgId === this.planInfoList[index].bgId
      );
      let totalAmount = 0;
      let budGet = this.budgetList[searchIndex];
      this.updateProductList.forEach((item) => {
        if (item.bgId === budGet.bgId) {
          totalAmount += parseFloat(item.bdgTotlePrice);
        }
      });
      this.budgetList[searchIndex].useMoney =
        parseFloat(totalAmount).toFixed(2);
      this.budgetList[searchIndex].surpMoney = parseFloat(
        budGet.totalAmount - this.budgetList[searchIndex].useMoney
      ).toFixed(2);
    },
    handleChange(index, newValue) {
      this.changeMoney(index, newValue);
    },
    changeMoney(index, value) {
      const budIndex = this.budgetList.findIndex(
        (item) => item.bgId === this.planInfoList[index].bgId
      );
      let budget = this.budgetList[budIndex];

      const proIndex = this.updateProductList.findIndex(
        (item) => item.id === this.planInfoList[index].id
      );
      let obj = this.planInfoList[index];

      if (proIndex !== -1) {
        this.updateProductList.splice(proIndex, 1);
        this.updateProductList.splice(proIndex, 0, obj);
      } else {
        this.updateProductList.push(obj);
      }

      let flag = 0;

      console.log(
        "updateProductList:" + JSON.stringify(this.updateProductList)
      );
      this.updateProductList.forEach((item) => {
        if (item.id != this.planInfoList[index].id) {
          if (item.bgId === this.planInfoList[index].bgId) {
            flag += parseFloat(item.bdgTotlePrice);
          }
        }
      });
      let cassFlag = parseFloat(budget.totalAmount - flag).toFixed(2);

      let price = this.planInfoList[index].bdgSinglePrice;
      let number = this.planInfoList[index].reqNumber;
      let productTotal = price * number;
      let totalAmount =
        productTotal + productTotal * (this.planInfoList[index].taxRate / 100);
      console.log("total:" + totalAmount);
      console.log("cassFlag:" + cassFlag);
      console.log("flag:" + flag);
      if (totalAmount < cassFlag) {
        this.planInfoList[index].bdgTotlePrice =
          parseFloat(totalAmount).toFixed(2);
        this.saveRowProduct(index);
      } else {
        let backMoney = this.planInfoList[index].bdgTotlePrice;
        if (parseFloat(this.budgetList[budIndex].useMoney) > 0) {
          this.budgetList[budIndex].useMoney = parseFloat(flag).toFixed(2);
          this.budgetList[budIndex].surpMoney = parseFloat(cassFlag).toFixed(2);
        }
        this.planInfoList[index].bdgTotlePrice = 0;
        this.planInfoList[index].reqNumber = 0;
        this.$modal.msgError("超出预算金额.请输入正确的数值");
      }
    },

    myFormatTime(time) {
      return utils.myformatter(new Date(time));
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    //创建采购计划
    createPlan() {
      addPurs(this.purForm).then((response) => {
        if (response.msg != "操作成功") {
          this.addPurPlanStatu = false;
        }
      });
    },

    checkSelectable(row, index) {
      return this.productOpenCode == 1;
    },

    saveBudGetList() {
      budList(this.budgetList).then((response) => {
        if (response.msg != "操作成功") {
          this.addPurPlanStatu = false;
        }
        this.addBudGetList = [];
      });
    },
    //新增采购商品信息
    addBatchPlanInfo() {
      addBatchPlanInfo(this.planInfoList).then((res) => {});
    },
    generatePurPlan() {
      this.$refs["purForm"].validate((valid) => {
        if (valid) {
          if (this.upload.fileSecuss.length == 0) {
            this.$modal.msgError("未上传采购附件");
            return;
          }
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          console.log("test:" + JSON.stringify(this.planInfoList));
          this.createPlan();
          if (this.addPurPlanStatu) {
            this.saveBudGetList();
            this.addBatchPlanInfo();
            this.addRecord();
            this.$modal.msgSuccess("提交成功");
            loading.close();
            this.$router.push("/purs/purs");
          } else {
            this.$modal.msgError("提交失败");
            loading.close();
          }
        } else {
          this.$modal.msgError("数据填充不完整");
        }
      });
    },
    //添加采购流程
    addRecord() {
      this.records.planCode = this.purForm.planCode;
      this.records.createName = sessionStorage.getItem("userName");
      this.records.deptName = sessionStorage.getItem("deptName");
      this.records.appType = 1;
      this.records.appName = "采购提交";
      this.records.appStatu = 2;
      addRecords(this.records).then((res) => {});
    },

    //获取采购计划编号
    getPlanCode() {
      this.purForm.planType = 1;
      let tableName = "pur_prod_plan";
      getPurCode(tableName).then((response) => {
        this.purForm.planCode = response.data.encodeNow;
      });
    },
    //获取预算编号
    getBudGetCode() {
      let tableName = "pur_prod_budget";
      getPurCode(tableName).then((response) => {
        this.budGetCodeObj = response.data;
        let str = this.budGetCodeObj.encodeNow.slice(
          this.budGetCodeObj.tableCode.length,
          this.budGetCodeObj.encodeNow.length
        );
        this.budGetCodeIndex = str;
      });
    },

    indexMethod(index) {
      // 根据需要自定义序号生成方式，这里只是简单返回索引+1
      return index + 1;
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        bgId: null,
        planCode: null,
        bgName: null,
        totalAmount: null,
        useMoney: null,
        surpMoney: null,
        createPost: null,
      };
      this.resetForm("form");
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.getBudGetCode();
      this.submitStatu = 1;
      this.open = true;
      this.title = "添加采购";
    },
    /** 修改按钮操作 */
    handleUpdate(index, row) {
      this.submitStatu = 2;
      this.updateObjIndex = index;

      if (row.bgName) {
        this.form.bgName = row.bgName;
      }
      if (row.createPost) {
        this.form.createPost = row.createPost;
      }
      if (row.totalAmount) {
        this.form.totalAmount = row.totalAmount;
      }
      this.open = true;
    },
    handleDelete(index, row) {
      this.$modal
        .confirm(
          '是否删除预算编号为"' + this.budgetList[index].bgId + '"的数据项？'
        )
        .then(() => {
          const searchIndex = this.planInfoList.findIndex(
            (item) => item.bgId === this.budgetList[index].bgId
          );

          if (searchIndex !== -1) {
            this.$modal.msgError("该预算编号正在被使用.删除失败");
          } else {
            this.$modal.msgSuccess("删除成功");
            this.budgetList.splice(index, 1);
          }
        })
        .catch((err) => {
          // 捕获任何可能的错误
          console.error("删除过程中出现错误:", err);
          // 在这里处理错误，例如显示错误消息或者其他操作
        });
    },
    /** 提交按钮 */
    submitForm() {
      if (
        this.form.createPost == null ||
        this.form.totalAmount == null ||
        this.form.bgName == null
      ) {
        this.$modal.msgError("信息填充不完整.添加失败");
      } else {
        let obj = {};
        obj.createPost = this.form.createPost;
        obj.totalAmount = this.form.totalAmount;
        obj.planCode = this.purForm.planCode;
        obj.bgName = this.form.bgName;
        obj.surpMoney = this.form.totalAmount;
        if (this.submitStatu == 1) {
          obj.bgId = this.budGetCodeObj.tableCode + this.budGetCodeIndex;
          obj.useMoney = parseFloat(0);
          this.budgetList.push(obj);
          this.addBudGetList.push(obj);
          this.budGetCodeIndex =
            parseInt(this.budGetCodeIndex) + parseInt(this.budGetCodeObj.step);
        } else {
          obj.bgId = this.budgetList[this.updateObjIndex].bgId;
          this.budgetList.splice(this.updateObjIndex, 1);
          this.budgetList.splice(this.updateObjIndex, 0, obj);
        }

        this.reset();
        this.open = false;
      }
    },
    /**表格合并 */
    productObjectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2) {
        // 假设根据第一列进行合并
        if (rowIndex > 0 && row.bgId === this.planInfoList[rowIndex - 1].bgId) {
          return {
            rowspan: 0,
            colspan: 0,
          };
        } else {
          let rowspan = 1;
          for (let i = rowIndex + 1; i < this.planInfoList.length; i++) {
            if (row.bgId === this.planInfoList[i].bgId) {
              rowspan++;
            } else {
              break;
            }
          }
          return {
            rowspan: rowspan,
            colspan: 1,
          };
        }
      }
    },

    /**表格合并 */
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 3) {
        // 假设根据第一列进行合并
        if (
          rowIndex > 0 &&
          row.createPost === this.budgetList[rowIndex - 1].createPost
        ) {
          return {
            rowspan: 0,
            colspan: 0,
          };
        } else {
          let rowspan = 1;
          for (let i = rowIndex + 1; i < this.budgetList.length; i++) {
            if (row.createPost === this.budgetList[i].createPost) {
              rowspan++;
            } else {
              break;
            }
          }
          return {
            rowspan: rowspan,
            colspan: 1,
          };
        }
      }
    },

    /**文件 */
    //文件移除钩子
    removeFile(file, fileList) {
      console.log();
    },
    //文件删除之前的钩子
    beforeRemove(file, fileList, itme) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      // return this.$confirm(`确定移除 ${file.name}？`);
      const index = fileList.indexOf(file);
      let fileSuccess = null;
      if (fileList[index].response != null) {
        fileSuccess = fileList[index].response.data.data.name;
      } else {
        loading.close();
        this.$modal.msgError("文件未上传.删除失败!");
      }

      let obj = this.upload.fileSecuss.find(
        (item) => item.name === fileSuccess
      );

      console.log("obj:" + obj.fileId);
      deleteFile(obj.name).then((response) => {});

      delPlanFiles(obj.fileId).then((res) => {
        this.$modal.msgSuccess("文件删除成功");
        loading.close();
      });
    },
    //上传文件之前
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$modal.msgError("文件大小不可超过10MB");
      }
      return isLt2M;
    },
    //文件上传失败
    uploadError(err, file, fileList) {
      this.upload.isUploading = false;
      this.$modal.msgError(err);
    },
    exceedingMaximumLimit(file, fileList) {
      this.$modal.msgError("最多上传文件5个！！");
    },
    // 文件提交处理
    submitUpload() {
      this.$refs.upload.submit();
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      let test = true;
      if (response.code == 200) {
        let fileObj = response.data.data;
        let tableName = "pur_prod_plan_file";
        getPurCode(tableName).then((res) => {
          this.fileForm.fileId = res.data.encodeNow;
          fileObj.fileId = res.data.encodeNow;
        });
        this.addFileList.push(fileObj);
        this.upload.fileSecuss.push(fileObj);
        this.fileForm.planCode = this.purForm.planCode;
        this.fileForm.fileName = fileObj.name;
        this.fileForm.filePath = fileObj.url;
        this.fileForm.fileId = fileObj.fileId;

        setTimeout(() => {
          addPlanFiles(this.fileForm).then((response) => {
            console.log("fileForm:" + JSON.stringify(this.fileForm));
            if (response.msg == "操作成功") {
              this.$modal.msgSuccess("文件上传成功");
            } else {
              this.$modal.msgSuccess("文件上传失败!");
            }
          });
        }, 2000);
      }
      this.upload.isUploading = false;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    openFullScreen2() {},
  },
};
</script>
  
<style scope>
.add-pur-box {
  width: 100%;
  height: 1700px;
  background-color: #f1f4f8;
}

.box-head {
  width: 100%;
  height: 60px;
  box-sizing: border-box;
  background-color: #ffffff;
  border: 1px solid #ccc;
  line-height: 60px;
  font-family: "宋体";
  font-weight: bold;
  font-style: italic;
  text-indent: 68px;
  background-image: url("../../../image/我的计划.png");
  background-repeat: no-repeat;
  background-size: 30px 30px;
  background-position: 30px center;
}

.box-plan-info {
  width: 1300px;
  height: 450px;
  border: 1px solid #ccc;
  background-color: #ffffff;
  margin: 20px auto;
  border-radius: 18px;
}

.box-plan-info > div:nth-of-type(1) {
  width: 100px;
  height: 40px;
  line-height: 40px;
  text-indent: 20px;
  font-weight: bold;
  color: black;
}

.basic-info {
  width: 400px;
  height: 40px;
  margin: 20px 100px;
  float: left;
}

.basic-info > span {
  font-family: "仿宋";
  font-weight: bold;
  margin-left: 40px;
}

.plan-main-box .el-input.is-disabled .el-input__inner {
  background-color: inherit; /* 继承父级背景色，或设置成你需要的颜色 */
  color: black;
  font-family: "仿宋";
  font-weight: bold;
}

.my_style {
  width: 200px;
  margin-left: 20px;
  border-bottom: 1px solid gray;
  color: black;
}

.budget-box {
  width: 1300px;
  height: 450px;
  border: 1px solid #ccc;
  background-color: #ffffff;
  margin: 20px auto;
  border-radius: 18px;
  overflow: auto;
}

.budget-box > div:nth-of-type(1) {
  width: 100px;
  height: 40px;
  line-height: 40px;
  text-indent: 20px;
  font-weight: bold;
  color: black;
}
.budget-info {
  width: 1200px;
  height: 300px;
  margin: 20px auto;
}

.my-tab-style {
  width: 120px;
  text-align: center;
  border-bottom: 1px solid gray;
  color: black;
  margin-left: 12px;
}

.my-tab-style > .el-input__inner {
  background-color: inherit; /* 继承父级背景色，或设置成你需要的颜色 */
  font-family: "仿宋";
  font-weight: bold;
}

.pro-box .el-input__inner {
  text-align: center;
  font-weight: bold;
}

.budget-box .el-input__inner {
  text-align: center;
  font-weight: bold;
}

.pro-box {
  width: 1300px;
  height: 500px;
  border: 1px solid #ccc;
  background-color: #ffffff;
  margin: 20px auto;
  border-radius: 18px;
  overflow: scroll;
}

.pro-box > div:nth-of-type(1) {
  width: 100px;
  height: 40px;
  line-height: 40px;
  text-indent: 20px;
  font-weight: bold;
  color: black;
}

.planPro-info {
  width: 1200px;
  height: 300px;
  margin: 20px auto;
}

.budGetSty {
  width: 100px;
  height: 40px;
  background-image: url("../../../image/搜索.png");
  background-repeat: no-repeat;
  background-size: 20px 20px;
  background-position: 54px center;
}
.budGetSty:hover {
  cursor: pointer;
  opacity: 0.7;
}

.planProSty {
  width: 100px;
  height: 40px;
  background-image: url("../../../image/产品管理.png");
  background-repeat: no-repeat;
  background-size: 28px 28px;
  background-position: 75px center;
}
.planProSty:hover {
  cursor: pointer;
  opacity: 0.7;
}

.el-inputNumber-style {
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 5px;
  text-align: center;
  width: 150px;
}
.datePickerStyle {
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 5px;
  text-align: left;
}

.plan-main-box .el-input input {
  border: none;
  outline: none;
  box-shadow: none;
}

.planPro-info .el-input__inner {
  background-color: inherit; /* 继承父级背景色，或设置成你需要的颜色 */
  color: black;
  font-family: "仿宋";
  font-weight: bold;
}
.budGet-el-table {
  width: 1200px;
}

.Pro-BudGet-Sty:hover {
  cursor: pointer;
  opacity: 0.7;

  color: red;
}

.my-form-style .el-form-item__label {
  color: black;
  font-family: "仿宋";
  font-weight: bold;
  font-size: 16px;
}

.my-form-style .el-form-item {
  width: 500px;
}

.product-style:hover {
  cursor: pointer;
  opacity: 0.7;

  color: red;
}

.submit-box {
  width: 1300px;
  height: 120px;
  margin: 0 auto;
}
</style>